<template>
  <div>
    <el-row>
      <el-col :span="3">
        <el-upload
          :action="url+'/files/upload?uploadPath='+currentPath"
          :before-remove="beforeRemove"
          multiple
          name="file"
          :on-success="uploadSuccess"
          :on-error="uploadFailed"
          :show-file-list="false"
        >
          <el-button type="primary">
            <i class="el-icon-upload2"></i> 上传
          </el-button>
        </el-upload>
      </el-col>
      <el-col :span="1" :pull="1">
        <el-button plain @click="inputDir">
          <i class="el-icon-folder-add"></i> 新建文件夹
        </el-button>
      </el-col>
      <el-col :span="6" :offset="13">
        <el-input placeholder="请输入搜索内容" prefix-icon="el-icon-search" v-model="input2"></el-input>
      </el-col>
    </el-row>

    <el-row class="tip" type="flex" justify="space-between" style="margin-top: 30px">
      <el-col :span="5">
        <el-breadcrumb separator="/">
          <el-breadcrumb-item><a href="/">全部文件</a></el-breadcrumb-item>
          <el-breadcrumb-item v-for="(link, index) in links"><a
            @click="previewFile(index, 'nav')">{{ link.filename }}</a></el-breadcrumb-item>
        </el-breadcrumb>
      </el-col>
      <el-col :span="3">全部加载完成，共{{ count }}个文件</el-col>
    </el-row>

    <el-table :data="files" style="width: 100%" :default-sort="{prop: 'updateTime', order: 'descending'}">
      <el-table-column prop="filename" label="文件名" width="180" sortable>
        <template slot-scope="scope">
          <div class="file-icon" :class="getFileType(scope.row.fileType)"></div>
          <el-link style="font-size: 14px;margin-bottom: 10px"
                   @click="previewFile(scope.row.filename, scope.row.fileType)">{{ scope.row.filename }}
          </el-link>
        </template>
      </el-table-column>
      <el-table-column prop="size" label="大小" width="180" sortable></el-table-column>
      <el-table-column prop="updateTime" label="修改日期" sortable></el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button type="primary" icon="el-icon-download" @click="download(scope.row.filename)">下载</el-button>
          <el-button type="danger" icon="el-icon-delete" @click="deleteFile(scope.row.filename)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script>
export default {
  name: "FileContent",
  data() {
    return {
      url: "",
      input2: "",
      count: 1,
      files: [{filename: "后台未开", size: "1MB", updateTime: "2020-1-1", fileType: "default"}],
      links: [],
      currentPath: ""
    };
  },
  methods: {
    previewFile(filename, fileType) {
      let targetUrl;
      console.log("preview方法执行")
      console.log("currentPath:" + this.currentPath)
      // 如果是文件夹
      if (fileType === "folder") {
        let filePath = filename;
        if (this.links.length !== 0) {
          filePath = this.links.slice(-1)[0].filePath + "/" + filename;
        }
        // 更新显示数据
        this.getAllFile(filePath)
        // 更新当前工作目录
        this.currentPath = filePath
        console.log("currentPath改变为:" + this.currentPath)
        // 存储每个目录文件的路径
        this.links.push({"filename": filename, "filePath": filePath})
        // 如果是普通文件　
      } else if (fileType === "nav"){
        const index = filename;
        this.links = this.links.slice(0, index + 1)
        this.getAllFile(this.links[index].filePath)
        this.currentPath = this.links[index].filePath
        console.log("currentPath改变为:" + this.currentPath)
      }else {
        if (this.currentPath !== "") {
          targetUrl = this.url + '/files/download?filename=' + this.currentPath + "/" + filename + '&onlineOpen=' + true;
        } else {
          targetUrl = this.url + '/files/download?filename=' + filename + '&onlineOpen=' + true;
        }
        const a = document.createElement('a');
        a.target = "_blank";
        a.href = targetUrl;
        a.click();
      }

    },
    inputDir() {
      this.$prompt('请输入文件夹名字', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputPattern: /\S/,
        inputErrorMessage: '无法使用该名字作为文件夹名'
      }).then(({value}) => {
        this.$axios.get("/files/mkdir?dirName=" + value + "&currentPath=" + this.currentPath).then(res => {
          if (res.data === "success") {
            this.$message({
              type: 'success',
              message: '创建成功！'
            });
            // 更新文件
            this.getAllFile(this.currentPath)
          }
        }).catch(err => {
          this.$message({
            type: 'error',
            message: '创建失败！原因未知 '
          });
        })
      })
    },
    getAllFile(filePath) {
      if (filePath === undefined) {
        this.$axios
          .get("/files/")
          .then(res => {
            console.log(res);
            this.files = res.data;
            this.count = res.data.length
            this.currentPath = ""
            this.links = []
          })
          .catch(err => {
            console.log(err);
          });
      } else {
        this.$axios
          .get("/files/?filePath=" + filePath)
          .then(res => {
            console.log(res);
            this.files = res.data;
            this.count = res.data.length
          })
          .catch(err => {
            console.log(err);
          });
      }

    }
    ,
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`);
    }
    ,
    uploadSuccess(response, file, fileList) {
      this.$message({
        message: "上传成功",
        type: "success"
      });
      this.getAllFile(this.currentPath);
    }
    ,
    uploadFailed(err, file, fileList) {
      // console.log(err)
      this.$message.error("上传失败");
    }
    ,
    download(filename) {
      window.location.href =
        this.$axios.defaults.baseURL + "/files/download?filename=" + filename;
    }
    ,
    deleteFile(filename) {
      this.$confirm("确认删除？").then(() => {
        this.$axios
          .get("/files/delete?filename=" + filename)
          .then(res => {
            this.$message({
              message: "删除成功",
              type: "success"
            });
            this.getAllFile();
          })
          .catch(err => {
            this.$message.error("删除失败");
          });
      });
    }
    ,
    getFileType(originType) {
      let supportedType = ['default', 'folder', 'pdf', 'compress_file', "web",
        'video', 'audio', 'picture', 'doc', 'txt', 'torrent', 'ppt', 'code']
      if (supportedType.indexOf(originType) !== -1) {
        return originType
      }
      return 'default'
    }
    ,
  },
  mounted() {
    this.getAllFile();
    this.url = this.$axios.defaults.baseURL;
    // console.log(window.location.href)
  }
};
</script>

<style>
el-input {
  padding: 0;
}

.tip {
  margin-top: 5px;
  font-size: 12px;
  color: gray;
}

.file-icon {
  display: inline-block;
  background-image: url(../assets/file_icons.png);
  background-repeat: no-repeat;
  width: 26px;
  height: 23px;
  margin-top: 8px;
}

.default {
  background-position: -596px -566px;
}

.folder {
  background-position: -594px -862px;
}

.pdf {
  background-position: -596px -136px;
}

.compress_file {
  background-position: -596px -1664px;
}

.video {
  background-position: -596px -1630px;
}

.audio {
  background-position: -596px -442px;
}

.picture {
  background-position: -596px -306px;
}

.doc {
  background-position: -596px -170px;
}

.txt {
  background-position: -596px -102px;
}

.ppt {
  background-position: -596px -204px;
}

.torrent {
  background-position: -596px 0px;
}

.web {
  background-position: -594px -1458px;
}

.code {
  background-position: -596px -1424px;
}
</style>
